package net.onceface.application.impl;

import java.util.List;

import javax.inject.Named;

import org.springframework.transaction.annotation.Transactional;

import net.onceface.application.FeatureApplication;
import net.onceface.application.assembler.FeatureAssembler;
import net.onceface.application.dto.FeatureDTO;
import net.onceface.core.domain.Feature;
import net.onceface.infra.querychannel.QueryChannelService;
import net.onceface.infra.spring.ioc.InstanceFactory;

@Named
@Transactional
@SuppressWarnings("unchecked")
public class FeatureApplicationImpl implements FeatureApplication{

	private QueryChannelService queryChannel;
	
	private QueryChannelService getQueryChannelService() {
		if (queryChannel == null) {
			queryChannel = InstanceFactory.getInstance(
					QueryChannelService.class, "queryChannel");
		}
		return queryChannel;
	}
	@Override
	public FeatureDTO getFeature(Long id) {
		// TODO Auto-generated method stub
		Feature feature = Feature.get(Feature.class, id);
		return FeatureAssembler.toDTO(feature);
	}

	@Override
	public List<FeatureDTO> getAllFeature() {
		// TODO Auto-generated method stub
		return FeatureAssembler.toDTOs(Feature.findAll(Feature.class));
	}

	@Override
	public void updateFeature(FeatureDTO featureDTO) {
		// TODO Auto-generated method stub
		FeatureAssembler.toEntity(featureDTO).save();
	}

	@Override
	public void saveFeature(FeatureDTO featureDTO) {
		// TODO Auto-generated method stub
		FeatureAssembler.toEntity(featureDTO).save();
	}

	@Override
	public List<FeatureDTO> getIndexFeature() {
		StringBuilder jpql = new StringBuilder("SELECT new net.onceface.application.dto.FeatureDTO(_feature) FROM Feature _feature")
		.append(" WHERE _feature.sortOrder >= 100")
		.append(" AND _feature.sortOrder < 1000")
		.append(" AND _feature.disabled > 0")
		.append(" AND _feature.startTime < NOW()")
		.append(" AND _feature.abolishDate > NOW()")
		.append(" ORDER BY _feature.sortOrder DESC");
		return getQueryChannelService().createJpqlQuery(jpql.toString()).list();
	}
	@Override
	public List<FeatureDTO> getHotFeature() {
		StringBuilder jpql = new StringBuilder("SELECT new net.onceface.application.dto.FeatureDTO(_feature.id, _feature.version, _feature.name, _feature.picture) FROM Feature _feature")
		.append(" WHERE _feature.sortOrder >= 1000")
		.append(" AND _feature.disabled > 0")
		.append(" AND _feature.startTime < NOW()")
		.append(" AND _feature.abolishDate > NOW()")
		.append(" ORDER BY _feature.sortOrder DESC");
		return getQueryChannelService().createJpqlQuery(jpql.toString()).list();
		
	}

}
